package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.Validator;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    protected Validator validator;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysUserPostService userPostService;

    @Autowired
    private ISysUserRoleService userRoleService;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        MPJLambdaWrapper<SysUser> wrapper = new MPJLambdaWrapper<SysUser>()
                .selectAll(SysUser.class)
                .select(SysDept::getDeptName, SysDept::getLeader)
                .leftJoin(SysDept.class, SysDept::getDeptId, SysUser::getDeptId)
                .eq(SysUser::getDelFlag, "0");

        if (user.getUserId() != null && user.getUserId() != 0) {
            wrapper.eq(SysUser::getUserId, user.getUserId());
        }
        if (StringUtils.isNotEmpty(user.getUserName())) {
            wrapper.like(SysUser::getUserName, user.getUserName());
        }
        if (StringUtils.isNotEmpty(user.getStatus())) {
            wrapper.eq(SysUser::getStatus, user.getStatus());
        }
        if (StringUtils.isNotEmpty(user.getPhonenumber())) {
            wrapper.like(SysUser::getPhonenumber, user.getPhonenumber());
        }
        // 时间范围查询
        if (StringUtils.isNotNull(user.getParams())) {
            Map<String, Object> params = user.getParams();
            if (params.get("beginTime") != null) {
                wrapper.ge(SysUser::getCreateTime, params.get("beginTime"));
            }
            if (params.get("endTime") != null) {
                wrapper.le(SysUser::getCreateTime, params.get("endTime"));
            }
        }
        // 部门查询
        if (user.getDeptId() != null && user.getDeptId() != 0) {
            // 先查询所有子部门ID
            List<Long> subDeptIds = getSubDeptIds(user.getDeptId());

            if (!subDeptIds.isEmpty()) {
                // 如果有子部门，使用 IN 条件
                wrapper.in(SysUser::getDeptId, subDeptIds);
            } else {
                // 如果没有子部门，只查询当前部门
                wrapper.eq(SysUser::getDeptId, user.getDeptId());
            }
        }
        // 关键：将SysDept映射到getDept字段
        wrapper.selectAssociation(SysDept.class, SysUser::getDept);
        return userMapper.selectJoinList(SysUser.class, wrapper);
    }

    /**
     * 获取部门及其所有子部门的ID
     */
    private List<Long> getSubDeptIds(Long deptId) {
        List<Long> result = new ArrayList<>();
        // 包含当前部门
        result.add(deptId);

        // 递归查询所有子部门
        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDept::getParentId, deptId);
        List<SysDept> children = deptMapper.selectList(wrapper);

        for (SysDept child : children) {
            result.addAll(getSubDeptIds(child.getDeptId()));
        }

        return result;
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user) {
        MPJLambdaWrapper<SysUser> wrapper = new MPJLambdaWrapper<SysUser>()
                .distinct()
                .select(SysUser::getUserId, SysUser::getDeptId, SysUser::getUserName,
                        SysUser::getNickName, SysUser::getEmail, SysUser::getPhonenumber,
                        SysUser::getStatus, SysUser::getCreateTime)
                .leftJoin(SysDept.class, SysDept::getDeptId, SysUser::getDeptId)
                .leftJoin(SysUserRole.class, SysUserRole::getUserId, SysUser::getUserId)
                .leftJoin(SysRole.class, SysRole::getRoleId, SysUserRole::getRoleId)
                .eq(SysUser::getDelFlag, "0")
                .eq(SysRole::getRoleId, user.getRoleId());

        if (StringUtils.isNotEmpty(user.getUserName())) {
            wrapper.like(SysUser::getUserName, user.getUserName());
        }
        if (StringUtils.isNotEmpty(user.getPhonenumber())) {
            wrapper.like(SysUser::getPhonenumber, user.getPhonenumber());
        }
        // 关键：将SysDept映射到getDept字段
        wrapper.selectAssociation(SysDept.class, SysUser::getDept);
        return userMapper.selectJoinList(SysUser.class, wrapper);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user) {
        MPJLambdaWrapper<SysUser> wrapper = new MPJLambdaWrapper<SysUser>()
                .distinct()
                .select(SysUser::getUserId, SysUser::getDeptId, SysUser::getUserName,
                        SysUser::getNickName, SysUser::getEmail, SysUser::getPhonenumber,
                        SysUser::getStatus, SysUser::getCreateTime)
                .leftJoin(SysDept.class, SysDept::getDeptId, SysUser::getDeptId)
                .eq(SysUser::getDelFlag, "0");

        // 处理角色过滤条件 - 使用Lambda条件完全避免SQL
        if (user.getRoleId() != null) {
            // 构建子查询条件
            MPJLambdaWrapper<SysUserRole> subWrapper = new MPJLambdaWrapper<SysUserRole>()
                    .select(SysUserRole::getUserId)
                    .eq(SysUserRole::getRoleId, user.getRoleId());

            List<Long> allocatedUserIds = userRoleMapper.selectList(subWrapper)
                    .stream()
                    .map(SysUserRole::getUserId)
                    .collect(Collectors.toList());

            // 安全处理空列表
            if (!allocatedUserIds.isEmpty()) {
                wrapper.notIn(SysUser::getUserId, allocatedUserIds);
            }
        }

        if (StringUtils.isNotEmpty(user.getUserName())) {
            wrapper.like(SysUser::getUserName, user.getUserName());
        }
        if (StringUtils.isNotEmpty(user.getPhonenumber())) {
            wrapper.like(SysUser::getPhonenumber, user.getPhonenumber());
        }

        wrapper.selectAssociation(SysDept.class, SysUser::getDept);

        return userMapper.selectJoinList(SysUser.class, wrapper);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        // 第一步：查询用户基本信息（包含部门信息）
        MPJLambdaWrapper<SysUser> userWrapper = new MPJLambdaWrapper<SysUser>()
                .selectAll(SysUser.class)
                .select(SysDept::getDeptName, SysDept::getParentId, SysDept::getAncestors,
                        SysDept::getOrderNum, SysDept::getLeader, SysDept::getStatus)
                .leftJoin(SysDept.class, SysDept::getDeptId, SysUser::getDeptId)
                .eq(SysUser::getUserName, userName)
                .eq(SysUser::getDelFlag, "0");

        userWrapper.selectAssociation(SysDept.class, SysUser::getDept);
        SysUser user = baseMapper.selectJoinOne(SysUser.class, userWrapper);

        if (user == null) {
            return null;
        }

        // 第二步：单独查询用户的角色信息
        List<SysRole> roles = roleService.selectRolesByUserId(user.getUserId());
        user.setRoles(roles);

        return user;
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        MPJLambdaWrapper<SysUser> wrapper = new MPJLambdaWrapper<SysUser>()
                .selectAll(SysUser.class)
                .select(SysDept::getDeptName, SysDept::getParentId, SysDept::getAncestors,
                        SysDept::getOrderNum, SysDept::getLeader, SysDept::getStatus)
                .select(SysRole::getRoleId, SysRole::getRoleName, SysRole::getRoleKey,
                        SysRole::getRoleSort, SysRole::getDataScope, SysRole::getStatus)
                .leftJoin(SysDept.class, SysDept::getDeptId, SysUser::getDeptId)
                .leftJoin(SysUserRole.class, SysUserRole::getUserId, SysUser::getUserId)
                .leftJoin(SysRole.class, SysRole::getRoleId, SysUserRole::getRoleId)
                .eq(SysUser::getUserId, userId)
                .distinct(); // 添加去重，解决多角色导致的重复问题

        // 关键：将SysDept映射到getDept字段
        wrapper.selectAssociation(SysDept.class, SysUser::getDept);
        return userMapper.selectJoinOne(SysUser.class, wrapper);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleService.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postService.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserName, user.getUserName())
                .eq(SysUser::getDelFlag, "0")
                .last("limit 1");

        SysUser info = getOne(wrapper);
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getPhonenumber, user.getPhonenumber())
                .eq(SysUser::getDelFlag, "0")
                .last("limit 1");

        SysUser info = getOne(wrapper);
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getEmail, user.getEmail())
                .eq(SysUser::getDelFlag, "0")
                .last("limit 1");

        SysUser info = getOne(wrapper);
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = baseMapper.insert(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return baseMapper.insert(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleService.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostService.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return baseMapper.updateById(user);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleService.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        LambdaUpdateWrapper<SysUser> wrapper = new LambdaUpdateWrapper<SysUser>()
                .set(SysUser::getStatus, user.getStatus())
                .set(SysUser::getUpdateTime, new Date())
                .eq(SysUser::getUserId, user.getUserId());
        return update(wrapper) ? 1 : 0;
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return baseMapper.updateById(user);
    }

    /**
     * 修改用户头像
     *
     * @param userId 用户ID
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(Long userId, String avatar) {
        LambdaUpdateWrapper<SysUser> wrapper = new LambdaUpdateWrapper<SysUser>()
                .set(SysUser::getAvatar, avatar)
                .set(SysUser::getUpdateTime, new Date())
                .eq(SysUser::getUserId, userId);

        return update(wrapper);
    }

    /**
     * 更新用户登录信息（IP和登录时间）
     *
     * @param userId    用户ID
     * @param loginIp   登录IP地址
     * @param loginDate 登录时间
     * @return 结果
     */
    @Override
    public void updateLoginInfo(Long userId, String loginIp, Date loginDate) {
        LambdaUpdateWrapper<SysUser> wrapper = new LambdaUpdateWrapper<SysUser>()
                .set(SysUser::getLoginIp, loginIp)
                .set(SysUser::getLoginDate, loginDate)
                .eq(SysUser::getUserId, userId);

        update(wrapper);
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        LambdaUpdateWrapper<SysUser> wrapper = new LambdaUpdateWrapper<SysUser>()
                .set(SysUser::getPwdUpdateDate, new Date())
                .set(SysUser::getPassword, user.getPassword())
                .set(SysUser::getUpdateTime, new Date())
                .eq(SysUser::getUserId, user.getUserId());

        return update(wrapper) ? 1 : 0;
    }

    /**
     * 重置用户密码
     *
     * @param userId   用户ID
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(Long userId, String password) {
        LambdaUpdateWrapper<SysUser> wrapper = new LambdaUpdateWrapper<SysUser>()
                .set(SysUser::getPwdUpdateDate, new Date())
                .set(SysUser::getPassword, password)
                .set(SysUser::getUpdateTime, new Date())
                .eq(SysUser::getUserId, userId);

        return update(wrapper) ? 1 : 0;
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostService.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleService.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleService.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostService.deleteUserPostByUserId(userId);
        return baseMapper.deleteById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleService.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostService.deleteUserPost(userIds);
        return baseMapper.deleteBatchIds(Arrays.asList(userIds));
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        // 导入逻辑保持不变，因为涉及复杂业务逻辑
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getUserName, user.getUserName());
                SysUser u = getOne(wrapper);
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    deptService.checkDeptDataScope(user.getDeptId());
                    String password = configService.selectConfigByKey("sys.user.initPassword");
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    save(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    deptService.checkDeptDataScope(user.getDeptId());
                    user.setUserId(u.getUserId());
                    user.setDeptId(u.getDeptId());
                    user.setUpdateBy(operName);
                    updateById(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
